package textProcessor;

import exceptions.NoSuchFileException;
import exceptions.WrongEncodingException;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class IOManager {

	private static final Charset encoding = Charset.forName("UTF-8");

	private static void checkPath(String path) throws NoSuchFileException, IllegalArgumentException {
        if (path == null)
            throw new IllegalArgumentException("Argument value null is not allowed");
		File file = new File(path);
		if (!(file.exists() && file.isFile()))
			throw new NoSuchFileException(String.format("File not found: %s",
					file.getAbsolutePath()));
	}

	public static String readTextFromFile(String path)
			throws WrongEncodingException, IOException, NoSuchFileException, IllegalArgumentException {
		checkPath(path);
		StringBuilder text = new StringBuilder();
		try (BufferedReader reader = Files.newBufferedReader(Paths.get(path),
				encoding)) {
			String line;
			try {
				while ((line = reader.readLine()) != null)
					text.append(line);
			} catch (MalformedInputException ex) {
				throw new WrongEncodingException("Wrong input file encoding",
						ex.getCause());
			}
		}
		return text.toString();
	}

	public static void saveToFile(String path,
                                  List<List<String>> listOfAllAnagrams) throws IOException,
            NoSuchFileException {
		checkPath(path);
        if (listOfAllAnagrams == null)
            throw new IllegalArgumentException("Argument value null is not allowed");
		try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(path),
				encoding)) {
			for (List<String> anagrams : listOfAllAnagrams) {
				writer.write(anagrams.toString());
				writer.newLine();
			}
		}
	}
}
